# -*- coding: utf-8 -*-
import re
import psutil
import requests
from logger_setup import get_logger

net_tool_logger = get_logger("net_tool")


def get_userinfo():
    """获取设备网络信息"""
    if not is_network_port_connected():
        net_tool_logger.info("网络接口未连接，无法获取设备网络信息")
        return "网络接口未连接，无法获取设备网络信息"
    if verify("https://www.baidu.com"):
        net_tool_logger.info('已连接网络')
        return True
    else:
        try:
            html = requests.get(r"http://translate.google.cn/translate_a/element.js?&cb=googleTranslate")
            html = html.text
            href = re.findall(r"href='([^']+)'", html)
            if len(href) != 0:
                wlanuserip = re.findall(r"wlanuserip=([^&]+)", href[0])[0]
                wlanacname = re.findall(r"wlanacname=([^&]+)", href[0])[0]
                ssid_nasip = re.findall(r"ssid=&nasip=([^&]+)", href[0])[0]
                snmpagentip_mac = re.findall(r"snmpagentip=&mac=([^&]+)", href[0])[0]
                wirelessv2_url = re.findall(r"t=wireless-v2&url=([^&]+)", href[0])[0]
                apmac_nasid = re.findall(r"apmac=&nasid=([^&]+)", href[0])[0]
                vid = re.findall(r"vid=([^&]+)", href[0])[0]
                port = re.findall(r"port=([^&]+)", href[0])[0]
                nasportid = re.findall(r"nasportid=([^&]+)", href[0])[0]
                data = {"wlanuserip": wlanuserip, "wlanacname": wlanacname, "ssid_nasip": ssid_nasip,
                        "snmpagentip_mac": snmpagentip_mac, "wirelessv2_url": wirelessv2_url,
                        "apmac_nasid": apmac_nasid,
                        "vid": vid, "port": port, "nasportid": nasportid}
                href = href[0]
                net_tool_logger.info('成功获取info')
                return href, data
            net_tool_logger.info('info为空')
        except Exception as e:
            net_tool_logger.warning('get_userinfo发生错误')
            net_tool_logger.error(e)


def verify(url):
    """验证"""
    try:
        requests.get(url, timeout=5)
        return True
    except:
        return False


def is_network_port_connected():
    """
    检查物理网络接口是否连接

    Returns:
        bool: 物理接口已连接返回True，未连接返回False
    """
    # 虚拟接口关键词
    virtual_keywords = [
        'virtual', 'vmware', 'virtualbox', 'vbox', 'hyper-v',
        'veth', 'docker', 'wsl', 'tap', 'tun', 'loopback',
        'ppp', 'vpn', 'zerotier', 'tailscale', 'bluetooth'
    ]

    # 物理接口模式
    physical_patterns = [
        r'^eth\d+', r'^en[p|s|o]\w+', r'^wlan\d+', r'^wl\d+',
        r'^以太网', r'^ethernet', r'^wi-fi', r'^wireless', r'^en\d+'
    ]

    def is_physical_interface(name):
        """判断是否为物理接口"""
        name_lower = name.lower()

        # 排除虚拟接口
        for keyword in virtual_keywords:
            if keyword in name_lower:
                return False
        if name_lower == 'lo' or 'loopback' in name_lower:
            return False

        # 匹配物理接口模式
        for pattern in physical_patterns:
            if re.match(pattern, name, re.IGNORECASE):
                return True

        # 进一步分析
        physical_indicators = ['ethernet', 'wi-fi', 'wireless', 'lan', 'wan']
        if not any(char.isdigit() for char in name) and len(name.split()) == 1:
            return False
        for indicator in physical_indicators:
            if indicator in name_lower:
                return True

        return False

    try:
        # 检查所有网络接口
        stats = psutil.net_if_stats()
        for interface_name, status in stats.items():
            if status.isup and is_physical_interface(interface_name):
                return True
        return False

    except Exception as e:
        net_tool_logger.warning("is_network_port_connected错误")
        net_tool_logger.error(e)
        return False
